package org.lease.web.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.lease.common.result.Result;
import org.lease.model.dto.SystemUserItemDTO;
import org.lease.model.entity.SystemUser;
import org.lease.model.enums.BaseStatus;
import org.lease.model.query.SystemUserPageQuery;
import org.lease.service.SystemUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

@Tag(name = "员工管理")
@RestController
@RequestMapping("/admin/system/user")
public class SystemUserController {
    @Autowired
    private SystemUserService systemUserService;

    @Operation(summary = "分页条件查询员工信息")
    @GetMapping("/page")
    public Result<IPage<SystemUserItemDTO>> pageQuery(SystemUserPageQuery query) {
        IPage<SystemUserItemDTO> page = systemUserService.pageQuery(query);
        return Result.success(page);
    }

    @Operation(summary = "校验用户名是否可用")
    @GetMapping("/isUserNameAvailable")
    public Result<Boolean> isUserNameAvailable(String username) {
        boolean bool = systemUserService.isUserNameAvailable(username);
        return Result.success(bool);
    }

    @Operation(summary = "保存或更新员工信息")
    @PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(SystemUser systemUser) {
        if (systemUser.getPassword() != null) {
            systemUser.setPassword(DigestUtils.md5DigestAsHex(systemUser.getPassword().getBytes()));
        }
        systemUserService.saveOrUpdate(systemUser);
        return Result.success();
    }

    @Operation(summary = "根据 ID 删除员工信息")
    @DeleteMapping("/deleteById")
    public Result removeById(Long id) {
        systemUserService.removeById(id);
        return Result.success();
    }

    @Operation(summary = "根据ID修改后台用户状态")
    @PostMapping("/updateStatusByUserId")
    public Result updateStatusByUserId(@RequestParam Long id, @RequestParam BaseStatus status) {
        LambdaUpdateWrapper<SystemUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SystemUser::getId, id);
        updateWrapper.set(SystemUser::getStatus, status);
        systemUserService.update(updateWrapper);
        return Result.success();
    }
}
